package com.zhixiao.user.controller

import cn.dev33.satoken.util.SaResult
import com.zhixiao.user.model.User
import com.zhixiao.user.model.dto.LoginDTO
import com.zhixiao.user.model.dto.RegisterDTO
import com.zhixiao.user.model.dto.UserInfoDTO
import com.zhixiao.user.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

private const val USERNAME_PATTERN = "[a-zA-Z0-9_]{2,16}"
private const val PASSWORD_PATTERN = "[a-zA-Z0-9_\\p{Punct}]{6,16}"
private const val REGISTER_SUCCESS_MSG = "注册成功"
private const val REGISTER_FAIL_MSG = "注册失败, 请稍后再试"
private const val INVALID_NULL_MSG = "用户名或密码不能为空"
private const val INVALID_CREDENTIALS_MSG = "用户名或密码不合法"
private const val INVALID_LOGIN_MSG = "用户名或密码错误"


@RestController
@RequestMapping("/account")
class UserController {

    @Autowired
    private var userService: UserService? = null

    /**
     * 注册接口
     * @param registerUser 注册信息
     * @return SaResult 注册结果
     */
    @PostMapping("/register")
    fun register(@RequestBody registerUser: RegisterDTO): SaResult {
        validate(registerUser.username, registerUser.password)

        // 调用注册逻辑
        val result = userService?.register(registerUser)
        return if (result == true) SaResult.ok(REGISTER_SUCCESS_MSG) else SaResult.error(REGISTER_FAIL_MSG)
    }

    /**
     * 登录接口
     * @param loginUser 登录信息
     * @return SaResult 登录结果, 若成功, 返回用户信息
     */
    @PostMapping("/login")
    fun login(@RequestBody loginUser: LoginDTO): SaResult {
        validate(loginUser.username, loginUser.password)

        // 调用登录逻辑
        val user: User = userService?.login(loginUser.username, loginUser.password) ?:
        throw IllegalArgumentException(INVALID_LOGIN_MSG)

        // 对齐数据, 隐藏系统敏感信息
        val userInfo = UserInfoDTO(
            user.username,
            user.nickname,
            user.age,
            user.gender,
            user.role
        )

        return SaResult.ok().setData(userInfo)
    }

    private fun validate(username: String, password: String) {
        // 判空
        if (username.isEmpty() || password.isEmpty()) {
            throw IllegalArgumentException(INVALID_NULL_MSG)
        }
        // 判断合法性
        if (!username.matches(Regex(USERNAME_PATTERN)) ||
            !password.matches(Regex(PASSWORD_PATTERN))
        ) {
            throw IllegalArgumentException(INVALID_CREDENTIALS_MSG)
        }
    }
}